<template>
  <van-button :loading="loading" :icon="value? 'star': 'star-o'" :class="{ collected:value }" @click="onCollect" />
</template>

<script>
import { addCollect, deleteCollect } from '@/api/article.js'
export default {
  name: 'CollectArticle',
  data() {
    return {
      loading: false
    }
  },
  props: {
    value: {
      type: Boolean,
      required: true
    },
    articleId: {
      type: [String, Number, Object],
      required: true
    }
  },
  methods: {
    async onCollect() {
      this.loading = true
      try {
        // 判断是收藏状态和未收藏状态 来调用不同的接口
        if (this.value) {
          // 已收藏
          await deleteCollect(this.articleId)
          this.$toast.success('取消收藏成功')
        } else {
          // 未收藏
          await addCollect(this.articleId)
          this.$toast.success('收藏成功')
        }
        // 更新视图
        this.$emit('input', !this.value)
      } catch (err) {
        // 错误提示
        this.$toast.fail('收藏失败')
      }
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
.collected {
  .van-icon {
    color: #ffa500;
  }
}
</style>
